//
//  LTSceneryDetailController.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-29.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTSceneryDetailController.h"

@interface LTSceneryDetailController ()
{
    UIWebView* _webView;
    NSString* _scenerySummary;
    NSString* _buyNotice;//购票须知
    NSString* _traffic;//交通
    NSString* _address;
    NSString* _sceneryId;
    UIActivityIndicatorView *_activityView;
    UILabel* _loadMoreTip;
    
}
@end

@implementation LTSceneryDetailController


-(void)viewWillAppear:(BOOL)animated{
  
   [self show:0];
}

- (IBAction)btnBackClicked:(UIBarButtonItem *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)segmentControlValueChanged:(UISegmentedControl *)sender {
    //[self clearAllUIWebViewData];
    //[self showInWebView:[NSString stringWithFormat:@"%d",self.segControl.selectedSegmentIndex]];
   
    [self show:self.segControl.selectedSegmentIndex];
}
- (void)clearAllUIWebViewData {
    // Clear the webview cache...
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [self removeApplicationLibraryDirectoryWithDirectory:@"Caches"];
    [self removeApplicationLibraryDirectoryWithDirectory:@"WebKit"];
    // Empty the cookie jar...
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
    [self removeApplicationLibraryDirectoryWithDirectory:@"Cookies"];
}

- (void)removeApplicationLibraryDirectoryWithDirectory:(NSString *)dirName {
    NSString *dir = [[[[NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES) lastObject] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:dirName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:dir]) {
        [[NSFileManager defaultManager] removeItemAtPath:dir error:nil];
    }
}

-(void)show:(NSInteger)index{

    if(index==0){
        //显示简介
      
        [self showInWebView:[NSString stringWithFormat:@"地址：<h4>%@</h4><br/>%@",_address,_scenerySummary]];

    }else if(index==1){
        //显示购票须知
        if(_buyNotice==nil){
            [self loadSceneryDetail];
        }
        [self showInWebView:_buyNotice];
    }else if(index==2){
        //显示交通
        if(_traffic==nil){
            [self loadSceneryTraffic];
        }
        if(_address !=nil){
            [self showInWebView:[NSString stringWithFormat:@"地址：<h4>%@</h4><br/>%@",_address,_traffic]];
        }else{
            [self showInWebView:_traffic];
        }
    }
    
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _webView=[[UIWebView alloc]initWithFrame:self.view.frame];
    _webView.delegate=self;
    _webView.backgroundColor=[UIColor clearColor];
    _sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
    _scenerySummary=[self.dictScenery objectForKey:@"scenerySummary"];
     _address=[self.dictScenery objectForKey:@"sceneryAddress"];
    
    CGRect frame=_webView.frame;
    if(IsIOS7){
        frame.origin.y=60;
    }
    frame.size.height=frame.size.height-60;
    [_webView setFrame:frame];
    [self.view addSubview:_webView];
    
    //[self show:0];
    
}

-(void)showInWebView:(NSString*)htmlData{
    NSMutableString* str=[[NSMutableString alloc]init];
    
    if(htmlData==nil || [htmlData isEqualToString:@""]){
        [str appendString:@"<h5>暂无信息。</h5>"];
    }else{
        
    [str appendString:htmlData];
    }
    NSData* data=[ str dataUsingEncoding:NSUTF8StringEncoding];
    //_webView.clearsContextBeforeDrawing;
    [_webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    
    _webView.delegate=nil;
    _webView=nil;
   
}

-(void)loadSceneryDetail{
    
    
    
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_detail.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    if([CommonConfigUtil existFileWithLocalPath:localJson]){
       
        //从本地获取
        [self readSceneryDetailFromLocal];
        /*
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localJson error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladDataTimeSecond]){
                
                //从网络获取
                [self readSceneryDetailFromNet];
                
            }else{
                //从本地获取
                [self readSceneryDetailFromLocal];
            }
        }else{
            //从网络获取
            [self readSceneryDetailFromNet];
        }*/
        
        
    }else{
        //从网络读取
        [self readSceneryDetailFromNet];
    }
    
    
}
-(void)readSceneryDetailFromLocal{
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_detail.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    NSData* jsonData=[NSData dataWithContentsOfFile:localJson];
    if(jsonData !=nil){
        NSError* error;
        NSDictionary* dictImage=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || dictImage==nil ) {
            [self readSceneryDetailFromNet];//从网络获取
        }else{
            [self parseSceneryDetail:dictImage];
            
        }
    }
    
}

-(void)readSceneryDetailFromNet{
  [self createActivityIndicatorView];
   [NSThread detachNewThreadSelector:@selector(readSceneryDetailFromNetThread) toTarget:self withObject:nil];
}
-(void)readSceneryDetailFromNetThread{
    NSString* xmlData=   [LocalTravelRequest getSceneryDetail:_sceneryId cc:@"2"];
    
    SceneryDetailParse* parse=[[SceneryDetailParse alloc]initWithXmlData:xmlData];
    
    NSDictionary* dict=[parse getScenaryDetail];
    [self parseSceneryDetail:dict];
    parse=nil;
    [NSThread detachNewThreadSelector:@selector(writeSceneryDetailToLocal:) toTarget:self withObject:dict];
    
    [self show:1];
    
    [self stopActivityIndicatorView];
}
-(void)writeSceneryDetailToLocal:(NSDictionary*)dict{
    if(dict==nil || dict.count==0)return ;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@_detail.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    [CommonConfigUtil writeJsonToLocal:dict localFile:localCityJson];
    
}
-(void)parseSceneryDetail:(NSDictionary*)dict{
    if(dict !=nil){
        //_sceneryIntro=[dict objectForKey:@"intro"];
        _buyNotice=[dict objectForKey:@"buyNotice"];
        _address=[dict objectForKey:@"address"];
    }
    
    dict=nil;
    
}
-(void)readSceneryTrafficFromNet{
    [self createActivityIndicatorView];
     [NSThread detachNewThreadSelector:@selector(readSceneryTrafficFromNetThread) toTarget:self withObject:nil];
    
}
-(void)readSceneryTrafficFromNetThread{
    NSString* sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
    NSString* xmlData=   [LocalTravelRequest getSceneryTrafficInfo:sceneryId];
    SceneryTrafficParse* parse=[[SceneryTrafficParse alloc]initWithXmlData:xmlData];
    
    NSDictionary* dict=[parse getScenaryTraffic];
    [self parseSceneryTraffic:dict];
    parse=nil;
    
    [NSThread detachNewThreadSelector:@selector(writeSceneryTrafficToLocal:) toTarget:self withObject:dict];
    
    [self show:2];
    [self stopActivityIndicatorView];
    
}
-(void)writeSceneryTrafficToLocal:(NSDictionary*)dict{
    if(dict==nil || dict.count==0)return ;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@_traffic.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    [CommonConfigUtil writeJsonToLocal:dict localFile:localCityJson];
    
}
-(void)readSceneryTrafficFromLocal{
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_traffic.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    NSData* jsonData=[NSData dataWithContentsOfFile:localJson];
    if(jsonData !=nil){
        NSError* error;
        NSDictionary* dictImage=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || dictImage==nil ) {
            [self readSceneryTrafficFromNet];//从网络获取
        }else{
            [self parseSceneryTraffic:dictImage];
            
        }
    }
    
}
-(void)parseSceneryTraffic:(NSDictionary*)dict{
    
    if(dict !=nil){
        _traffic=[dict objectForKey:@"traffic"];
        if(_traffic==nil)_traffic=@"";
    }
    
    dict=nil;
}
-(void)loadSceneryTraffic{
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_traffic.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    if([CommonConfigUtil existFileWithLocalPath:localJson]){
        //从本地读取
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localJson error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladDataTimeSecond]){
                
                //从网络获取
                [self readSceneryTrafficFromNet];
                
            }else{
                //从本地获取
                [self readSceneryTrafficFromLocal];
            }
        }else{
            //从网络获取
            [self readSceneryTrafficFromNet];
        }
        
        
    }else{
        //从网络读取
        [self readSceneryTrafficFromNet];
    }
    
    
}
-(void)stopActivityIndicatorView{
    [_activityView stopAnimating];
    [_activityView removeFromSuperview];
    _loadMoreTip.hidden=YES;
    [_loadMoreTip removeFromSuperview];
    
}
-(void)createActivityIndicatorView{
    _activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityView.hidesWhenStopped=YES;
    CGRect activityFrame=_activityView.frame;
    activityFrame.origin.x=_webView.frame.size.width/2-50;
    activityFrame.origin.y=_webView.frame.size.height/2;
    
    [_activityView setFrame:activityFrame];
    
    _activityView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    
    
    
    _loadMoreTip=[[UILabel alloc] initWithFrame:CGRectMake(activityFrame.origin.x+30, activityFrame.origin.y+5, 100, 20)];
    
    _loadMoreTip.textAlignment=NSTextAlignmentCenter;
    
    _loadMoreTip.text=@"正在加载数据";
    _loadMoreTip.textColor=[UIColor redColor];
    _loadMoreTip.font=[UIFont systemFontOfSize:16];
    _loadMoreTip.backgroundColor=[UIColor clearColor];
    
    [_webView addSubview:_activityView];
    [_webView addSubview:_loadMoreTip];
    [_activityView startAnimating];
    _activityView.hidden=NO;
    _loadMoreTip.hidden=NO;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    LTTicketTableController* ticketCtr=segue.destinationViewController;
    ticketCtr.dictScenery=self.dictScenery;
    
}

-(void)dealloc{
    _webView.delegate=nil;
    _webView=nil;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
